import 'dart:convert';
import 'dart:developer' as developer;

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class ChatGPT {
  Future<String> query(String question) async {
    developer.log('发送gpt请求：$question');
    WidgetsFlutterBinding.ensureInitialized();
    // proxy -> "SOCKS5/SOCKS4/PROXY username:password@host:port;" or "DIRECT"
    // SocksProxy.initProxy(proxy: 'SOCKS5 127.0.0.1:7890');
    // SocksProxy.initProxy(proxy: 'SOCKS5 abc1:aaa712@120.27.201.81:7899');
    // SocksProxy.initProxy(proxy: 'SOCKS5 127.0.0.1:13659');
    // const openaiApiKey = "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";
    const openaiApiKey = "sk-Z5PGDlRqyjTMdiFhCdEeFf1967D04978B63c7312836c0b6b";
    const openaiBaseUrl = "https://api.fast-tunnel.one/v1/chat/completions";
    final dio = Dio();
    dio.options.headers.addAll({
      "Content-Type": "application/json",
      "Authorization": "Bearer $openaiApiKey"
    });
    Response<String> response =
        await dio.post(openaiBaseUrl, data: {
      // "model": "gpt-3.5-turbo",
      "model": "gpt-4-1106-preview",
      "messages": [
        {"role": "user", "content": question}
      ],
      "temperature": 0.7
    });
    print(response.toString());
    Map<String, dynamic> dataJson = jsonDecode(response.data ?? "");
    developer.log('gpt响应原生结果：$dataJson');
    return dataJson["choices"][0]["message"]["content"];
  }
}
